package vn.gq.tym.fragment;

import java.io.IOException;
import java.util.zip.GZIPInputStream;

import vn.gq.tym.storytemplate.R;
import vn.gq.udv.utils.IOUtils;
import vn.gq.udv.utils.Settings;
import android.annotation.SuppressLint;
import android.graphics.Picture;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebView.PictureListener;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.actionbarsherlock.app.SherlockFragment;

@SuppressWarnings("deprecation")
public class WebviewFragment extends SherlockFragment {

	private ViewGroup mViewGroup;
	private WebView mWebView;
	private ProgressBar mProgressBar;
	private String filePath;
	private Handler mHandler = new Handler();
	private Settings mSetting;
	private int mScrollYPos = 0;
	
	public static WebviewFragment newInstance(String filePath, int scrollY) {
		WebviewFragment f = new WebviewFragment();
		Bundle args = new Bundle();
		args.putString("URL", filePath);
		args.putInt("SCROLLY", scrollY);
		f.setArguments(args);
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		if (args != null) {
			filePath = args.getString("URL");
			mScrollYPos = args.getInt("SCROLLY", 0);
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		mSetting = new Settings(getActivity());
		int size = mSetting.getFontSize(0);
		
		
		mViewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_reader, container, false);
		
		mWebView = (WebView) mViewGroup.findViewById(R.id.webview);
		mWebView.setOnTouchListener((OnTouchListener) getActivity());
		mWebView.setVisibility(View.GONE);
		mProgressBar = (ProgressBar) mViewGroup.findViewById(R.id.progress);
		mProgressBar.setVisibility(View.VISIBLE);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setPictureListener(new PictureListener() {
			
			@Override
			@Deprecated
			public void onNewPicture(WebView arg0, Picture arg1) {
				mWebView.scrollTo(0, mScrollYPos);
			}
		});
		mWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mWebView.setVisibility(View.VISIBLE);
				mProgressBar.setVisibility(View.GONE);
			}
		});
		mWebView.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		if (size == 0) {
			mSetting.setFontSize(mWebView.getSettings().getDefaultFontSize());
		} else {
			mWebView.getSettings().setDefaultFontSize(size);
		}
		mWebView.setLongClickable(false);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					String data = IOUtils.convertStreamToString(new GZIPInputStream(getActivity().getAssets().open(filePath)));
					feedData(data);
				} catch (IOException e) {
					e.printStackTrace();
					feedData(String.format("Có lỗi xảy ra: %s", filePath));
				}
			}
		}).start();
		
		return mViewGroup;
	}
	
	public void feedData(final String data) {
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				String html = (mSetting.isNightMode()) ? getNightModeHtml(data) : getDayModeHtml(data);
				mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", null);
			}
		});
	}
	
	public String getNightModeHtml(String data) {
		String html = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
				"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">" +
				"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">" +
				"<meta content=\"text/html; charset=UTF-8\" />" +
				"<link rel=\"stylesheet\" type=\"text/css\" href=\"css/night-styles.css\" />" +
				"</head><body>" + data + "</body></html>";
		return html;
	}
	
	public String getDayModeHtml(String data) {
		String html = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
				"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">" +
				"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">" +
				"<meta content=\"text/html; charset=UTF-8\" />" +
				"<link rel=\"stylesheet\" type=\"text/css\" href=\"css/styles.css\" />" +
				"</head><body>" + data + "</body></html>";
		return html;
	}
}
